package com.study.s01.array;

public class MyOrderArray {
	
	private long[] array;
	//表示有效数据的长度
	private int elements;
	
	public MyOrderArray() {
		
		array = new long[50];
	}
	
	public MyOrderArray(int maxsize) {
		
		array = new long[maxsize];
	}
	
	/**
	 * 添加数据
	 */
	public void insert(long value) {
		
		int i;
		for (i = 0; i < elements; i++) {
			if(array[i] > value) {
				break;
			}
		}
		for(int j = elements; j > i; j-- ) {
			array[j] = array[j - 1];
		}
		array[i] = value;
		elements++;
	}
	
	/**
	 * 显示数据
	 */
	public void dispaly() {
		
		System.out.print("[ ");
		for (int i = 0; i < elements; i++) {
			System.out.print(array[i] + " ");
		}
		System.out.println("]");
	}
	
	/**
	 * 查找数据
	 */
	public int search(long value) {
		
		int i;
		for (i = 0; i < elements; i++) {
			if(value == array[i]) {
				break;
			}
		}
		if(i == elements) {
			return -1;
		} else {
			return i;
		}
	}
	
	/**
	 * 二分法查找数据
	 */
	public int searchUseBinary(long value) {
		
		int middle = 0;
		int low = 0;
		int pow = elements;
		
		while(true) {
			middle = (low + pow) / 2;
			if(array[middle] == value) {
				return middle;
			} else if (low > pow) {
				return -1;
			} else {
				if(array[middle] > value) {
					pow = middle - 1;
				} else {
					low = middle + 1;
				}
			}
		}
	}
	
	/**
	 * 查找数据，根据索引
	 */
	public long searchByIndex(int index) {
		
		if(index >= elements || index < 0) {
			throw new ArrayIndexOutOfBoundsException();
		} else {
			return array[index];
		}
	}
	
	/**
	 * 删除数据
	 */
	public void delete(int index) {
		
		if(index >= elements || index < 0) {
			throw new ArrayIndexOutOfBoundsException();
		} else {
			for(int i = index; i < elements; i++) {
				array[index] = array[index + 1];
			}
			elements--;
		}
	}
	
	/**
	 * 更新数据
	 */
	public void update(int index, int newValue) {
		
		if(index >= elements || index < 0) {
			throw new ArrayIndexOutOfBoundsException();
		} else {
			array[index] = newValue;
		}
	}
}
